import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RegisterUserServlet")
public class RegisterUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public RegisterUserServlet() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String name = request.getParameter("name");
		String surname = request.getParameter("surname");
		String email = request.getParameter("email");
		String login = request.getParameter("login");
		String password = request.getParameter("password1");
		String birthday = request.getParameter("birthday");
		
		try {
			//laczenie z baza danych
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/paliwa-krakow","root","root");
			Statement stmt = con.createStatement();
			//otrzymywanie maksymalnego id+1
			String queryId = "SELECT MAX(idUser)+1 as id FROM User";
			ResultSet rs = stmt.executeQuery(queryId);
			rs.next();
			String id = rs.getString("id");
			//wykonanie dodania klienta
			String queryAdd = "INSERT INTO User VALUES("+id+", '"
					+name+"', '"+surname+"', '"+email+"', '"+login+"', '"+password+"', '"+birthday+"', 1, NOW(), '/def');";
			int rs1 = stmt.executeUpdate(queryAdd);
			if( rs1==1 ) {
				response.sendRedirect("index.jsp");
			} else {
				response.sendRedirect("index.jsp?page=register");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
		out.close();
	}
}
